package com.example.demo.inteceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInteceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");//防止乱码!
        if(!(handler instanceof HandlerMethod)){
            return true;                    //如果不是指向方法，就放行,返回true
        }
        System.out.println("正在拦截login请求");
        //String header=request.getHeader("token");//获取请求头，名为token的内容，因为这里不写界面了，就不用这个做示范了
        String name = request.getParameter("username"); //获取输入的参数
        if (name == null) {
            response.getWriter().write("name为空");     //这里可以用自己封装的resopnseresult,具体看springjwt
            return false;              //这里为false就不执行下面的了
        }
        if (!name.equals("123")) {
            response.getWriter().write("name:" + name + "不合法");
            return false;              //这里为fasle下面一样不执行
        }
        System.out.println("prehandle放行!");
        return true;                  //必须有返回
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
